package com.jsz.peini.common.util.wxpay.query;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * @author Han Guohong
 * @version 2017-4-14 下午5:57:13
 * 类说明
 */
public class WeChatUtil {
	public static final String ENCODE  = "UTF-8";

	public static String sendGet(String url, String param, boolean isForm, String encode)throws IOException {
		String result = "";
		
		// 打开连接，并设置参数
		URL httpUrl = new URL(url);
		HttpURLConnection conn = (HttpURLConnection) httpUrl.openConnection();
		conn.setDoInput(true); // 设置可输入
		conn.setDoOutput(true);// 设置可输出
		conn.setRequestMethod("GET");//设置请求方式为GET
		if (isForm)
		conn.setRequestProperty("Content-type", "application/x-www-form-urlencoded");
		conn.connect();
		
		// 输出
		write(conn.getOutputStream(), param, encode);
		conn.getOutputStream().flush();
		conn.getOutputStream().close();
		
		//输入
		result = read(conn.getInputStream(), 1024, ENCODE);
		conn.getInputStream().close();
		
		// 关闭连接
		conn.disconnect();
		
		return result;
	}
	
	public static String read(InputStream in, int length, String encode) throws IOException {
        StringBuilder result = new StringBuilder();

        byte[] b = new byte[length];
        int len = -1;
        while (-1 != (len = in.read(b)))
            result.append(new String(b, 0, len, encode));

        return result.toString();
    }
	
	public static void write(OutputStream out, String msg, String encode) throws IOException {
        byte[] b = msg.getBytes(encode);
        out.write(b);
        out.flush();
    }
}
